import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.github.lnyocly.ai4j.interceptor.ErrorInterceptor;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletionResponse;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Ai4jTest {
    static String lang = "韩国韩语";
    static String targetLang = "kokr";


    static String fileName = "C:\\Users\\bin.yin\\Desktop\\deeptrip\\corpus-test.xlsx";
    static String result = "C:\\Users\\bin.yin\\Desktop\\deeptrip\\corpus-" + targetLang + ".xlsx";

    private static final String system = "你是OTA产品领域【" + lang + "】翻译质检专家。请你帮我评估我给出的原文和译文是否符合" + lang + "的口语表达方式。\n"
            + "Workflow:\n"
            + "1,输入原文和对应译文，输入格式为json格式，sourceText表示原文，transText表示译文。\n"
            // + "2.文本需要进行" + lang + "口语化润色才认为【可用】。\n\n"
            + "2.对话类的文本需要进行" + lang + "口语化润色才认为【可用】；其他文本的本地化翻译也认为【可用】；\n\n"

            + "3.直接返回评估结果，可用直接返回`✅`，不可用直接返回`❌`\n"
            + "Examples:\n"
            + "Input: {\"sourceText\":\"预定\",\"transText\":\"Booking\"}\n"
            + "Output: ✅";

    private static final String promptPattern = "“{0}”是[{1}]口语化的表达方式吗？";
    private static final String QUALITY_FORMAT = "“{0}”在" + lang + "中的表达是什么？下列翻译怎么样：“{1}”" ;

    public static void main(String[] args) throws Exception {
        // KimiChat testChat = new KimiChat(okHttpClient, "百科");
        // ChatCompletionResponse response = testChat.chat("你好是什么");
        // System.out.println(response.getChoices().get(0).getMessage().getContent().getText());

        // ===读写
        KimiChat kimiChat = new KimiChat(okHttpClient, system);
        // DeepseekChat kimiChat = new DeepseekChat(okHttpClient, system);
        Field targetField = CorpusEntity.class.getDeclaredField(targetLang);
        targetField.setAccessible(true);
        List<Object> dataList = new ArrayList<>();
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        EasyExcel.read(fileName, CorpusEntity.class, new AnalysisEventListener<CorpusEntity>() {
            @Override
            public void invoke(CorpusEntity corpus, AnalysisContext context) {
                dataList.add(corpus);
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    try {
                        Object target = targetField.get(corpus);
                        String userContent = MessageFormat.format(promptPattern, target, lang);

                        ChatCompletionResponse response = kimiChat.chat(userContent);
                        String qualityResult = response.getChoices().get(0).getMessage().getContent().getText();
                        corpus.setQualityResult(qualityResult);

                        if (!"✅".equals(qualityResult)) {
                            System.out.println(MessageFormat.format(QUALITY_FORMAT, corpus.getSource(), target));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, executorService);
                futures.add(future);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
        }).sheet().doRead();

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        try {
            allFutures.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdown();

        EasyExcel.write(result, CorpusEntity.class).includeColumnFieldNames(includeField)
                .sheet("0").doWrite(() -> dataList);
    }

    public static final OkHttpClient okHttpClient;
    public static Set<String> includeField = new LinkedHashSet<>();
    /** 线程池 */
    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    static {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor).addInterceptor(new ErrorInterceptor())
                .connectTimeout(300, TimeUnit.SECONDS).writeTimeout(300, TimeUnit.SECONDS)
                .readTimeout(300, TimeUnit.SECONDS)
                // .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1",10809)))
                .build();

        includeField.add("scene");
        includeField.add("key");
        includeField.add("source");
        includeField.add(targetLang);
        includeField.add("qualityResult");
    }


}
